package com.zjhb.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Criteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.zjhb.common.controller.ExcelUtil;
import com.zjhb.common.controller.ExportBean;
import com.zjhb.common.dao.BaseDao;
import com.zjhb.common.dao.Page;
import com.zjhb.common.enumutil.Area;
import com.zjhb.common.enumutil.Asets;
import com.zjhb.common.enumutil.UserTypes;
import com.zjhb.common.util.BeanCopy;
import com.zjhb.common.util.JbaRcode;
import com.zjhb.common.util.JwtUser;
import com.zjhb.common.util.ResourceUtil;
import com.zjhb.common.util.ResponseUtil;
import com.zjhb.common.util.StringMyUtil;
import com.zjhb.entity.AssetsEntity;
import com.zjhb.entity.DepartmentEntity;
import com.zjhb.entity.FileEntity;

import param.AssetParam;

@RestController
@RequestMapping("/assests")
public class AssestsController {

	@Autowired
	private BaseDao baseDao;

	@PostMapping("/save")
	public JSONObject save(HttpServletRequest req, AssetsEntity assets) throws Exception {
		if (!ResourceUtil.getCurrentUser().getUserType().equals(UserTypes.Admin.getKey())) {
			return ResponseUtil.getMap(ResponseUtil.OTHER_CODE, "您没有该权限", "");
		}
		JSONObject j = new JSONObject();
		if (StringMyUtil.isEmpty(assets.getDepartId())) {
			j = ResponseUtil.getMap(ResponseUtil.OTHER_CODE, "部门不能为空", "");
			return j;
		}
		if (StringMyUtil.isEmpty(assets.getId())) {
			DepartmentEntity dep = baseDao.getById(DepartmentEntity.class, assets.getDepartId());
			Criteria crt = baseDao.getCriteria(AssetsEntity.class);
			crt.add(Restrictions.eq("departId", dep.getId()));
			List<DepartmentEntity> list = crt.list();
			assets.setNumber(dep.getCode() + StringMyUtil.getNubmer(1 + list.size()));
			String code = StringMyUtil.getOrderIdByUUId();
			assets.setCode(code);
			FileEntity file = new FileEntity();
			file.setCreateTime(ResourceUtil.getNowTime());
			file.setFileId(JbaRcode.createBarcode(code, dep.getName()));
			file.setName(code + ".png");
			baseDao.save(file);
			assets.setCodeUrl("down" + "/" + file.getId());
			assets.setDepartName(dep.getName());
			assets.setCreateTime(ResourceUtil.getNowTime());
			assets.setCreateUser(ResourceUtil.getCurrentUser().getId());
			assets.setStatus(Asets.Use.getKey());
			if (StringMyUtil.isNotEmpty(assets.getToTime())) {
				assets.setToTime(ResourceUtil.getJsonTime(assets.getToTime()));
			}
			baseDao.save(assets);
			j = ResponseUtil.getMap(ResponseUtil.TRUE_CODE, "", "");
			return j;
		} else {
			AssetsEntity bean = baseDao.getById(AssetsEntity.class, assets.getId());
			BeanCopy.copyBean2Bean(bean, assets);
			baseDao.update(bean);
			j = ResponseUtil.getMap(ResponseUtil.TRUE_CODE, "", "");
			return j;
		}

	}

	@PostMapping("/delete/{id}")
	public JSONObject delete(HttpServletRequest req, @PathVariable String id) {
		if (!ResourceUtil.getCurrentUser().getUserType().equals(UserTypes.Admin.getKey())) {
			return ResponseUtil.getMap(ResponseUtil.OTHER_CODE, "您没有该权限", "");
		}
		JSONObject j = new JSONObject();
		AssetsEntity assetsEntity = baseDao.getById(AssetsEntity.class, id);
		assetsEntity.setStatus(Asets.Delete.getKey());
		baseDao.update(assetsEntity);
		j = ResponseUtil.getMap(ResponseUtil.TRUE_CODE, "", "");
		return j;
	}

	@PostMapping("/lose/{id}")
	public JSONObject lose(HttpServletRequest req, @PathVariable String id) {
		if (!ResourceUtil.getCurrentUser().getUserType().equals(UserTypes.Admin.getKey())) {
			return ResponseUtil.getMap(ResponseUtil.OTHER_CODE, "您没有该权限", "");
		}
		JSONObject j = new JSONObject();
		AssetsEntity assetsEntity = baseDao.getById(AssetsEntity.class, id);
		assetsEntity.setStatus(Asets.lose.getKey());
		baseDao.update(assetsEntity);
		j = ResponseUtil.getMap(ResponseUtil.TRUE_CODE, "", "");
		return j;
	}

	@PostMapping("/list")
	public JSONObject list(HttpServletRequest req, HttpServletResponse resp, AssetParam param) throws Exception {
		JSONObject j = new JSONObject();
		Page<AssetsEntity> page = new Page<>();
		JwtUser user = ResourceUtil.getCurrentUser();
		Criteria crt = baseDao.getCriteria(AssetsEntity.class);
		if (StringMyUtil.isNotEmpty(user.getDepartId())) {
			crt.add(Restrictions.eq("departId", user.getDepartId()));
		}
		if (StringMyUtil.isNotEmpty(param.getStatus())) {
			crt.add(Restrictions.eq("status", param.getStatus()));
		}
		if (StringMyUtil.isNotEmpty(param.getAreaId())) {
			crt.add(Restrictions.eq("areaId", param.getAreaId()));
		}
		if (StringMyUtil.isNotEmpty(param.getNumber())) {
			crt.add(Restrictions.like("code", param.getNumber(), MatchMode.ANYWHERE));
		}
		if (StringMyUtil.isNotEmpty(param.getName())) {
			crt.add(Restrictions.like("name", param.getName(), MatchMode.ANYWHERE));
		}
		crt.add(Restrictions.or(Restrictions.eq("status", Asets.lose.getKey()),
				Restrictions.eq("status", Asets.Use.getKey())));
		List<AssetsEntity> list = new ArrayList<>();
		crt.setMaxResults(param.getLimit());
		crt.setFirstResult(param.getOffset());
		crt.addOrder(Order.desc("status")).addOrder(Order.desc("createTime"));
		list = crt.list();

		Long totalNum = baseDao.getCount(crt);
		if (list.size() > 0) {
			for (AssetsEntity entity : list) {
				entity.setAreaName(Area.parse(entity.getAreaId()).getValue());
				entity.setStatusDesc(Asets.parse(entity.getStatus()).getValue());
			}
		}
		page.setRows(list);
		page.setTotal(totalNum);
		j = ResponseUtil.getMap(ResponseUtil.TRUE_CODE, "", page);
		return j;
	}

	@RequestMapping("/down")
	public void autodown(AssetParam param, HttpServletRequest request, HttpServletResponse resp) throws Exception {
		// 语言选择
		if (!ResourceUtil.validate(request)) {
			return;
		}
		JwtUser user = ResourceUtil.getCurrentUser();
		Criteria crt = baseDao.getCriteria(AssetsEntity.class);
		if (StringMyUtil.isNotEmpty(user.getDepartId())) {
			crt.add(Restrictions.eq("departId", user.getDepartId()));
		}
		if (StringMyUtil.isNotEmpty(param.getStatus())) {
			crt.add(Restrictions.eq("status", param.getStatus()));
		}
		if (StringMyUtil.isNotEmpty(param.getAreaId())) {
			crt.add(Restrictions.eq("areaId", param.getAreaId()));
		}
		if (StringMyUtil.isNotEmpty(param.getNumber())) {
			crt.add(Restrictions.like("number", param.getNumber(), MatchMode.ANYWHERE));
		}
		if (StringMyUtil.isNotEmpty(param.getName())) {
			crt.add(Restrictions.like("name", param.getName(), MatchMode.ANYWHERE));
		}
		crt.add(Restrictions.or(Restrictions.eq("status", Asets.lose.getKey()),
				Restrictions.eq("status", Asets.Use.getKey())));
		List<AssetsEntity> list = new ArrayList<>();
		list = crt.list();
		if (list.size() > 0) {
			for (AssetsEntity entity : list) {
				entity.setAreaName(Area.parse(entity.getAreaId()).getValue());
				entity.setStatusDesc(Asets.parse(entity.getStatus()).getValue());
			}
		}
		ExportBean<AssetsEntity> bean = new ExportBean<>();
		bean.setPoList(list);
		bean.setHeader(new String[] { "名称", "部门", "区域", "价值", "条形码", "状态", "配发时间" });
		bean.setHeaderSize(7);
		bean.setTitle("资产");
		resp.setHeader("Content-Disposition",
				"attachment;filename=" + new String("资产.xls".getBytes("gb2312"), "ISO8859-1"));
		ExcelUtil.exportFromBean(bean, resp.getOutputStream());

	}

}
